package com.kuang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kuang.exception.ServiceException;
import com.kuang.mapper.UserMapper;
import com.kuang.pojo.User;
import com.kuang.service.UserService;
import com.kuang.utils.TokenUtils;
import io.micrometer.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.*;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

    @Autowired
    UserMapper userMapper;


    @Override
    public User selectUserByUsername(User user) {

        User user1 = userMapper.selectUserByUsername(user);
        //生成token,userId用来放在token里，password用来生成token的验证器，来验证token
        String token = TokenUtils.createToken(String.valueOf(user1.getId()), user1.getPassword());
        user1.setToken(token);
        return user1;
    }

    @Override
    public boolean resetPassword(User user) {
        System.out.println(user);
        //查看用户名是否在数据库中
        User resUser = userMapper.selectUserByUsername(user);
        System.out.println(resUser);
        if(resUser.equals("")){
            throw new ServiceException("用户不存在");
        }
        if (!resUser.getPhone().equals(user.getPhone())){
            System.out.println("resUser:"+resUser.getPhone());
            System.out.println("user:"+user.getPhone());
            throw new ServiceException("验证错误");
        }
        //重置密码
        resUser.setPassword("123");
        userMapper.updateUser(resUser);
        return true;
    }

    /**
     * 重写save方法
     * @param entity
     * @return
     */
    @Override
    public boolean save(User entity) {
        //先拿这个name去查数据库，如果有重名的话就抛异常
        //添加条件查询器
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        //添加条件(select * from patient where username = #{username})
        wrapper.eq("username",entity.getUsername());
        List<User> users = userMapper.selectList(wrapper);

        if (!users.isEmpty()){
            System.out.println(users);
            throw new ServiceException("用户名重复");
        }
        //如果添加的用户password为空，则手动添加初始密码
        if (StringUtils.isBlank(entity.getPassword())){
            System.out.println("密码为空");
            entity.setPassword("123456789");
        }
        return super.save(entity);
    }
}
